package com.zj.base.permission.annotations;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by zhaojie on 2018/5/18.
 */
@SuppressWarnings("unused")
public class PermissionProcessUtils {

    public static <T extends Annotation> List<T> parseMethod(Class<?> clzz, Class<T> cls) {
        List<T> annotationSet = new ArrayList<>();
        try {
            for (Method method : clzz.getDeclaredMethods()) {
                T pan = method.getAnnotation(cls);
                if (pan != null) {
                    annotationSet.add(pan);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return annotationSet;
    }

    public static <T extends Annotation> T parseCls(Class<?> clzz, Class<T> cls) {
        // 判断类上是否有对应注解
        boolean clzHasAnno = clzz.isAnnotationPresent(cls);
        if (clzHasAnno) {
            // 获取类上的注解
            T annotation = clzz.getAnnotation(cls);
            if (annotation != null)
                return annotation;
        }
        return null;
    }

    public static <T extends Annotation> List<T> parseField(Class<?> clzz, Class<T> cls) {
        List<T> annotationSet = new ArrayList<>();
        Field[] fields = clzz.getDeclaredFields();
        for (Field field : fields) {
            boolean fieldHasAnno = field.isAnnotationPresent(cls);
            if (fieldHasAnno) {
                T fieldAnnotation = field.getAnnotation(cls);
                if (fieldAnnotation != null)
                    annotationSet.add(fieldAnnotation);
            }
        }
        return annotationSet;
    }
}
